package com.superhelper.printer.server.event;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

@Component
public class EventDispater {
    private static final Logger log = LoggerFactory.getLogger(EventDispater.class);

    @Autowired
    private PingEventProcessor pingProcessor;

    @Autowired
    private PrintEventResponseProcessor printRespProcessor;

    private static final int CMD_PING = 81, CMD_PRINT_RESP = 80;

    public void dispatch(ByteBuf buf, ChannelHandlerContext ctx) {
        if (buf.readableBytes() < 7) {
            log.info("invalid msg");
            return;
        }
        // byte[] bytes = new byte[buf.readableBytes()];
        // buf.readBytes(bytes);
        // for (byte b : bytes) {
        // System.out.println(b);
        // }
        // if (true) {
        // return;
        // }
        ByteBuf newBuf = buf.skipBytes(6);
        // byte[] bs = newBuf.
        int cmd = newBuf.readByte();
        // try {
        // if (CMD_PING == cmd) {
        // int orderSeq = newBuf.readShort();
        // printRespProcessor.process(orderSeq);
        // } else if (CMD_PRINT_RESP == cmd) {
        // int printerId = newBuf.readInt();
        // int printerStatus = newBuf.readByte();
        // pingProcessor.process(printerId, printerStatus, ctx);
        // } else {
        // log.info("unknown cmd:{}", cmd);
        // }
        // } catch (Exception e) {
        // log.error("error", e);
        // }
        try {
            // 8个字节表示是ping包
            if (CMD_PING == cmd) {
                int printerId = newBuf.readInt();
                int printerStatus = newBuf.readByte();
                pingProcessor.process(printerId, printerStatus, ctx);
            } else if (CMD_PRINT_RESP == cmd) {
                int orderSeq = newBuf.readShort();
                printRespProcessor.process(orderSeq);
            } else {
                log.info("unknown cmd:{}", cmd);
            }
        } catch (Exception e) {
            log.error("error", e);
        }
    }
}
